/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.forumdata.forums;

import domain.DomainController;
import domain.forumdata.Category;
import domain.forumdata.Forum;
import domain.forumdata.ForumCategory;
import domain.forumdata.SupportedForums;
import domain.forumdata.tag.Tag;
import domain.net.CaptchaUtils;
import domain.net.HTMLParser;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.text.html.HTML.Attribute;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import persistence.net.Client;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 *
 * Represents WarezBB.org
 */
@Deprecated
public class WarezBB extends Forum
{
    public static final String FORUM_BASE_URL = "http://www.warez-bb.org/";
    public static final String LOGIN_URL = "http://www.warez-bb.org/login.php";
    public static final String LOGIN_SUCCEED_CHECK = "You have successfully logged in";
    public static final String POST_SUCCEED_CHECK = "Your message has been entered successfully";
    public static final String VIEWTOPIC_INDICATOR = "viewtopic.php?p=";

    private Client client;

    /**
     * Default constructor. Initializes a new forum of type WarezBB.
     * @param forumName The name for the forum.
     * @param username The username.
     * @param password The password.
     * @param categories A list of assigned categories.
     */
    public WarezBB(String forumName, String username, char[] password, ArrayList<ForumCategory> categories)
    {
        super(SupportedForums.SUPPORTED_FORUMS[1], forumName, LOGIN_URL, username, password, categories);
    }

    /**
     * Starts posting to the forum.
     * @param cat The category to post to.
     * @param topicTitle The topic title of the new post.
     * @param topicSubtitle The topic subtitle or small description of the new post.
     * @param tag The tag to use.
     * @param post The post body of the new post.
     * @return True if the message has been posted, false otherwise.
     */
    @Override
    public boolean doPost(Category cat, String topicTitle, String topicSubtitle, Tag tag, String post)
    {
        //Create new client
        this.client = new Client();

        //Login
        DomainController.getInstance().getLogger().log(Level.INFO, "Logging in...");

        if(this.login())
        {
            //Get the correct new topic link
            String newTopicURL = "";
            for(ForumCategory fc : this.getCategories())
            {
                if(fc.getCategory().getName().equals(cat.getName()))
                {
                    newTopicURL = fc.getUrl();
                    break;
                }
            }

            //Post!
            DomainController.getInstance().getLogger().log(Level.INFO, "Creating new topic...");
            return this.post(newTopicURL, topicTitle, topicSubtitle, tag, post);
        }
        else
        {
            DomainController.getInstance().getLogger().log(Level.WARNING, "Login failed!");
        }
        return false;
    }

    /**
     * Tries to login at this forum.
     * @return True if the login was successful, false oterhwise.
     */
    private boolean login()
    {
        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", this.getUsername()));
            nameValuePairs.add(new BasicNameValuePair("password", new String(this.getPassword())));
            nameValuePairs.add(new BasicNameValuePair("autologin", "1"));
            nameValuePairs.add(new BasicNameValuePair("hideonline", "0"));
            nameValuePairs.add(new BasicNameValuePair("redirect", ""));
            nameValuePairs.add(new BasicNameValuePair("login", "Log in"));
            this.client.doPost(WarezBB.LOGIN_URL, nameValuePairs);

            //Check if the login has succeeded.
            if(this.client.getResponseContent().contains(WarezBB.LOGIN_SUCCEED_CHECK))
                return true;
            else
                return false;
        }
        catch(Exception e)
        {
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Login failed! ({0})", e.getMessage());
            return false;
        }
    }

    /**
     * Tries to post a new topic at this forum.
     * When successful, the method tries to find the link of the new topic and stores it.
     * @param url The url of the "new topic".
     * @param topicTitle The title for the new topic.
     * @param topicSubtitle The subtitle or small description for the new topic.
     * @param tag The tag to use.
     * @param post The message for the new topic.
     * @return True if the message has been posted, false otherwise.
     */
    private boolean post(String url, String topicTitle, String topicSubtitle, Tag tag, String post)
    {
        try
        {
            //We need to extract the VIA link, or else we'll get the
            //"General error" -> "No via-link to database."
            //Se we surf once to the link and download the page.
            this.client.doGet(url);
            String content = this.client.getResponseContent();

            List<String> via = HTMLParser.extractValueFromTag(new StringReader(content),
                                                        javax.swing.text.html.HTML.Tag.INPUT,
                                                        Attribute.NAME,
                                                        "via",
                                                        Attribute.VALUE);

            //We also need the SID, or we'll get the "invalid session" error.
            //<input type="hidden" name="sid" value="74433900156ed0df9ad833c6c70f97ba">
            List<String> sid = HTMLParser.extractValueFromTag(new StringReader(content),
                                                        javax.swing.text.html.HTML.Tag.INPUT,
                                                        Attribute.NAME,
                                                        "sid",
                                                        Attribute.VALUE);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            //subject=Testing+again..&description=testing...&tag_select=&addbbcode18=%23&addbbcode20=12&helpbox=Font+color%3A+%5Bcolor%3Dred%5Dtext%5B%2Fcolor%5D++Tip%3A+you+can+also+use+color%3D%23FF0000&message=blah+blah&safelinking-links=&captcha-type=recaptcha&link-password=&via=c22eeb5c800bd537da712998209347f2&attach_sig=on&poll_title=&add_poll_option_text=&poll_length=&mode=newtopic&sid=086aa7d0032c090623ba09e180f360b6&f=26&post=Submit
            //subject=Testing+again..
            //description=testing...
            //tag_select=
            //addbbcode18=%23
            //addbbcode20=12
            //helpbox=Font+color%3A+%5Bcolor%3Dred%5Dtext%5B%2Fcolor%5D++Tip%3A+you+can+also+use+color%3D%23FF0000
            //message=blah+blah
            //safelinking-links=
            //captcha-type=recaptcha
            //link-password=
            //via=c22eeb5c800bd537da712998209347f2
            //attach_sig=on
            //poll_title=
            //add_poll_option_text=
            //poll_length=
            //mode=newtopic
            //sid=086aa7d0032c090623ba09e180f360b6&f=26
            //post=Submit

            /*
             * Sometimes we need to enter a captcha code
             * recaptcha_response_field
             */
            if(content.contains("recaptcha_response_field"))
            {
                try
                {
                    DomainController.getInstance().getLogger().log(Level.INFO, "Found CAPTCHA for {0}", this.getForumName());
                    nameValuePairs.addAll(CaptchaUtils.evaluateRecaptcha(client, content));
                }
                catch(Exception e)
                {
                    DomainController.getInstance().getLogger().log(Level.WARNING, "Captcha error. {0}", e.getMessage());
                }
            }

            nameValuePairs.add(new BasicNameValuePair("subject", tag.getSynonyms()[0] + " " + topicTitle));
            nameValuePairs.add(new BasicNameValuePair("description", topicSubtitle));
            nameValuePairs.add(new BasicNameValuePair("tag_select", tag.getSynonyms()[0]));
            nameValuePairs.add(new BasicNameValuePair("message", post));
            nameValuePairs.add(new BasicNameValuePair("notify", "1"));
            nameValuePairs.add(new BasicNameValuePair("send_pm", "1"));
            nameValuePairs.add(new BasicNameValuePair("mode", "newtopic"));
            nameValuePairs.add(new BasicNameValuePair("via", via.get(0)));
            nameValuePairs.add(new BasicNameValuePair("sid", sid.get(0)));
            nameValuePairs.add(new BasicNameValuePair("f", url.split("&f=")[1]));
            nameValuePairs.add(new BasicNameValuePair("post", "Submit"));

            this.client.doPost(url, nameValuePairs);

            if(this.client.getResponseContent().contains(WarezBB.POST_SUCCEED_CHECK))
            {
                //Get the topic url.
                //<a href="viewtopic.php?p=48298403#48298403">Here</a>
                //href = viewtopic.php?p=48298403#48298403
                List<String> hrefs = HTMLParser.getHREF(new StringReader(this.client.getResponseContent()));
                String link = WarezBB.FORUM_BASE_URL;
                for(String s : hrefs)
                {
                    if(s != null && s.contains(WarezBB.VIEWTOPIC_INDICATOR))
                    {
                        link += s;
                        break;
                    }
                }
                DomainController.getInstance().getLastPostTopicURLResults().add(link);
                DomainController.getInstance().getLogger().log(Level.INFO, "SUCCESS! Got link: {0}", link);
                return true;
            }
            else
            {
                DomainController.getInstance().getLogger().log(Level.WARNING, "Posting failed!");
                DomainController.getInstance().getLogger().log(Level.INFO, "Got response: {0}", this.client.getResponseContent());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Posting failed! ({0})", e.getMessage());
        }
        return false;
    }

    @Override
    public boolean canLogin()
    {
        this.client = new Client();
        return this.login();
    }
}